<!--
 * @Author: dfh
 * @Date: 2024-03-28 10:01:59
 * @LastEditors: dfh
 * @Modified By: dfh
 * @describe: 
-->
<template>
    <view class="container">
        <BackWidget />
        <view class="header-wrap">
            <view class="txt-white-255 txt-w-6" style="font-style: italic;font-size: 60rpx;">汇率及时查</view>
            <view class="mt-20 txt-white-255 txt-32">汇率查询服务</view>
            <view class="card header-box">
                <view class="flex ai-center flex-1 jc-between" @click="onShowRateHandle('start')">
                    <view class="flex ai-center">
                        <image :src="forData2.currencyMaseterIcon" style="width:32rpx;height:24rpx" />
                        <text class="txt-black-34 txt-32 ml-20">{{ forData2.currencyMasterEn }}</text>
                        <text class="iconfont icon-arrow-right-bold"></text>
                    </view>
                    <view class="flex flex-col ai-end">
                        <text class="txt-black-102 txt-32">1</text>
                        <text class="txt-black-204 txt-16">{{ forData2.currencyMaseterCh }}</text>
                    </view>
                </view>
                <view class="line">
                    <text class="iconfont icon-zhuanhuan" @click="onRateSwitchHandle"></text>
                </view>
                <view class="flex ai-center flex-1 jc-between" @click="onShowRateHandle('end')">
                    <view class="flex ai-center">
                        <image :src="forData2.currencySlaveIcon" style="width:32rpx;height:24rpx" />
                        <text class="txt-black-34 txt-32 ml-20">{{ forData2.currencySlaveEn }}</text>
                        <text class="iconfont icon-arrow-right-bold"></text>
                    </view>
                    <view class="flex flex-col ai-end">
                        <text class="txt-black-102 txt-32">{{ forData2.exchangeRate }}</text>
                        <text class="txt-black-204 txt-16">{{ forData2.currencySlaveCh }}</text>
                    </view>
                </view>
            </view>
        </view>
        <view class="card charts-wrap">
            <view class="flex ai-center jc-between mb-20">
                <view class="flex flex-col">
                    <text class="txt-black-34 txt-32">1USB = 7.22CNY</text>
                    <text class="txt-black-102 txt-18">实时汇率</text>
                </view>
                <view class="share-wrap">
                    <text class="iconfont icon-share"></text>
                    <button class="share-btn" open-type="share">分享</button>
                </view>
            </view>
            <canvas canvas-id="CUJobWVbkvkknDXTvFUjMKVZxXkfWRVr" id="CUJobWVbkvkknDXTvFUjMKVZxXkfWRVr" class="charts"
                @touchend="tap" v-if="showChart"></canvas>
            <view class="nav-wrap">
                <view class="nav" v-for="(item, index) in navList" :key="index" :class="{ active: navIndex === index }"
                    @click="onNavItemClick(index)">
                    {{ item }}</view>
            </view>
        </view>
        <RateSelect ref="rateEle" :data='currencyGroupObj' @onConfirm="onRateSelectHandle" />
    </view>
</template>

<script>
import uCharts from '@qiun/ucharts'
import dayjs from 'dayjs'
import { exchangeRateHistoryList } from '@/services/exchangeRate'
import RateSelect from '@/pages/home/components/rate-select.vue';
import BackWidget from '@/components/back-widget/index.vue'
import { fetchCurrencyGroupList, fetchExchangeRate } from '@/services/home';
var uChartsInstance = {};
export default {
    components: {
        RateSelect,
        BackWidget
    },
    data() {
        return {
            showChart: true,
            cWidth: 640,
            cHeight: 500,
            navList: ['一个月', '二个月', '三个月', '四个月', '五个月'],
            navIndex: 0,
            currencyGroupObj: {},
            forData2: {
                currencyMasterEn: "USD",
                currencyMaseterCh: '美元',
                currencyMaseterIcon: '',
                currencySlaveEn: "CNY",
                currencySlaveCh: '人民币',
                currencySlaveIcon: '',
                exchangeRate: 0.00
            },
            formData: {
                from: "USD",
                to: "CNY",
                startDate: '',
                endDate: '',
            },
            statusBarH: 0,
            titleH: 0
        };
    },
    watch: {
        navIndex(newVal) {
            console.log('11111')
            this.formData.startDate = dayjs().subtract(newVal + 1, 'month').format('YYYY-MM-DD');
            this.getExchangeRateHistoryList();
        },
        'forData2.currencyMasterEn'() {
            this.formData.from = this.forData2.currencyMasterEn;
            this.formData.to = this.forData2.currencySlaveEn;
            this.getExchangeRateHistoryList();
        }
    },
    mounted() {
        this.getCurrencyGroupList();
        this.getExchangeRate();
    },
    onReady() {
        //这里的 750 对应 css .charts 的 width
        this.cWidth = uni.upx2px(640);
        //这里的 500 对应 css .charts 的 height
        this.cHeight = uni.upx2px(500);
        this.formData.startDate = dayjs().subtract(1, 'month').format('YYYY-MM-DD');
        this.formData.endDate = dayjs().format('YYYY-MM-DD');
        this.getExchangeRateHistoryList();
    },
    methods: {
        onShowRateHandle(type) {
            this.showChart = false;
            this.$refs['rateEle'].show(type);
        },
        async getCurrencyGroupList() {
            const { msg, status, data } = await fetchCurrencyGroupList();
            if (status === 1) {
                this.currencyGroupObj = data || {}
                if (data && data['C']) {
                    const item1 = data['U'].find(item => item.currencyEn === 'USD');
                    const item2 = data['C'].find(item => item.currencyEn === 'CNY');
                    this.forData2.currencyMaseterIcon = item1.currencyIcon
                    this.forData2.currencySlaveIcon = item2.currencyIcon
                }
            } else {
                showToast(msg || '获取利率分组')
            }
        },
        async getExchangeRate() {
            const { msg, status, data } = await fetchExchangeRate(this.forData2);
            if (status === 1) {
                this.forData2.exchangeRate = data.exchangeRate || 0.00
            } else {
                showToast(msg || '查询汇率出错')
            }
        },
        onRateSelectHandle({ type, data }) {
            if (type == 'start') {
                this.forData2.currencyMasterEn = data.currencyEn;
                this.forData2.currencyMaseterCh = data.currencyZn;
                this.forData2.currencyMaseterIcon = data.currencyIcon;
            } else {
                this.forData2.currencySlaveEn = data.currencyEn;
                this.forData2.currencySlaveCh = data.currencyZn;
                this.forData2.currencySlaveIcon = data.currencyIcon;
            }
            this.showChart = true;
            uChartsInstance['CUJobWVbkvkknDXTvFUjMKVZxXkfWRVr'].updateData();
            this.getExchangeRate();
        },

        onRateSwitchHandle() {
            const { currencyMasterEn, currencyMaseterCh, currencySlaveEn, currencySlaveCh, currencyMaseterIcon, currencySlaveIcon } = this.forData2;
            this.forData2.currencyMasterEn = currencySlaveEn;
            this.forData2.currencyMaseterCh = currencySlaveCh;
            this.forData2.currencyMaseterIcon = currencySlaveIcon;
            this.forData2.currencySlaveEn = currencyMasterEn;
            this.forData2.currencySlaveCh = currencyMaseterCh;
            this.forData2.currencySlaveIcon = currencyMaseterIcon;
            this.getExchangeRate();
        },
        onNavItemClick(index) {
            if (this.navIndex === index) return;
            this.navIndex = index;
        },
        async getExchangeRateHistoryList() {
            const { msg, status, data } = await exchangeRateHistoryList(this.formData);
            if (status === 1) {
                const categories = [];
                const seriesData = [];
                const keys = Object.keys(data || [])
                Object.entries(data || []).forEach((item, index) => {
                    const [k, v] = item;
                    if (index == 1 || index == keys.length - 2 || index == Math.ceil(keys.length / 2)) {
                        categories.push(k.slice(5));
                    } else {
                        categories.push('');
                    }
                    seriesData.push(v.toFixed(2));
                })
                let res = {
                    categories: categories,
                    series: [
                        {
                            name: "汇率",
                            legendShape: "circle",
                            color: "#51af4f",
                            pointShape: "none",
                            data: seriesData
                        }
                    ]
                };
                this.drawCharts('CUJobWVbkvkknDXTvFUjMKVZxXkfWRVr', res);
            } else {
                showToast(msg)
            }
        },

        drawCharts(id, data) {
            const ctx = uni.createCanvasContext(id, this);
            uChartsInstance[id] = new uCharts({
                type: "area",
                context: ctx,
                color: ["#d1f4d0", "#c1f1c1", "#b2edb1", "#a3e9a1", "#93e692", "#84e282", "#74df73", "#65db63", "#5bc559"],
                // padding: [15, 15, 0, 15],
                width: this.cWidth,
                height: this.cHeight,
                dataLabel: false,
                canvas2d: true,
                categories: data.categories,
                series: data.series,
                xAxis: {
                    disableGrid: true,
                },
                yAxis: {
                    gridColor: "rgba(101,219,99,0.8)",
                    disabled: false,
                    disableGrid: false,
                    gridType: 'dash',
                    dashLength: '4',
                    data: [{
                        axisLineColor: "#FFFFFF",
                    },],
                },
                legend: {
                    show: false,
                    position: "top",
                    float: "right",
                },
                extra: {
                    area: {
                        type: "curve",
                        opacity: 0.9,
                        addLine: true,
                        width: 2,
                        gradient: true,
                    }
                },
            });

        },
        tap(e) {
            uChartsInstance[e.target.id].touchLegend(e);
            uChartsInstance[e.target.id].showToolTip(e);
        }
    }
}
</script>

<style>
.icon-share {
    font-size: 38rpx;
    color: red;
    position: absolute;
    left: 10rpx;
    top: 6rpx;
}

.icon-zhuanhuan {
    position: absolute;
    font-size: 38rpx;
    color: white;
    left: 50%;
    margin-left: -10rpx;
    top: -16rpx;
    background-color: rgba(242, 242, 251, 1);
    width: 50rpx;
    text-align: center;
}
</style>
<style lang="scss" scoped>
.container {
    position: relative;
    width: 100vw;
    height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;

    background: rgba(241, 245, 251, 1);



    .header-wrap {
        position: relative;
        padding: 100rpx 30rpx 30rpx;
        box-sizing: border-box;
        width: 100%;
        height: 400rpx;
        border-radius: 0 0 20rpx 30rpx;
        background: linear-gradient(to right bottom, #84e282, #74df73, #65db63, #5bc559);
    }

    .card {
        border-radius: 20rpx;
        padding: 20rpx;
        background-color: white;
        box-sizing: border-box;
        width: 680rpx;
    }

    .header-box {
        display: flex;
        flex-direction: column;
        position: absolute;
        height: 200rpx;
        left: 50%;
        margin-left: -340rpx;
        bottom: -100rpx;

        .line {
            position: relative;
            width: 100%;
            height: 2rpx;
            background-color: rgba(242, 242, 251, 1);
        }
    }

    .charts-wrap {
        margin-top: 120rpx;

        .charts {
            width: 640rpx;
            height: 500rpx;
        }

        .share-wrap {
            position: relative;
            width: 120rpx;
            height: 50rpx;

            .share-btn {
                width: 120rpx;
                height: 50rpx;
                border-radius: 10rpx;
                font-size: 24rpx;
                background-color: #65db63;
                color: white;
                line-height: 50rpx;
                border: none;
            }
        }

        .nav-wrap {
            margin-top: 20rpx;
            background-color: rgba(204, 204, 204, 1);
            width: 100%;
            height: 66rpx;
            display: flex;
            align-items: center;
            box-sizing: border-box;
            justify-content: space-around;
            padding: 0 20rpx;

            .nav {
                width: 100rpx;
                height: 50rpx;
                border-radius: 10rpx;
                font-size: 20rpx;
                color: rgba(100, 101, 102, 1);
                line-height: 50rpx;
                text-align: center;

                &.active {
                    color: black;
                    font-size: 24rpx;
                    background-color: white;
                }
            }
        }
    }


}
</style>